package top.mcwebsite.playandroid.lib.markdown.utils

import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.flavours.gfm.GFMTokenTypes

fun parseLink(astNode: ASTNode, text: String): Pair<String, String> {
    var linkText: String = ""
    var linkDestination = ""
    astNode.children.forEach {
        when (it.type) {
            MarkdownElementTypes.LINK_TEXT -> {
                linkText = parseLinkText(it, text)
            }
            MarkdownElementTypes.LINK_DESTINATION -> {
                linkDestination = parseLinkDestination(it, text)
            }
        }
    }
    return linkText to linkDestination
}

fun parseLinkText(astNode: ASTNode, text: String): String {
    var linkText: String = ""
    for (node in astNode.children) {
        when (node.type) {
            MarkdownTokenTypes.TEXT -> {
                linkText = text.substring(node.startOffset, node.endOffset)
            }
        }
    }
    return linkText
}

fun parseLinkDestination(astNode: ASTNode, text: String): String {
    var linkDestination = ""
    astNode.children.forEach {
        if (it.type == MarkdownTokenTypes.TEXT) {
            linkDestination = text.substring(astNode.startOffset, astNode.endOffset)
        }
        if (it.type == GFMTokenTypes.GFM_AUTOLINK) {
            linkDestination = text.substring(astNode.startOffset, astNode.endOffset)
        }
    }
    return linkDestination
}